import React, {ReactNode, useEffect, useRef} from 'react'
import './index.less'

const Sticky: React.FC<{
    height: number //children元素的高度
    children: ReactNode
}> = ({height, children}) => {
    const placeholder = useRef<HTMLDivElement | null>(null)
    const content = useRef<HTMLDivElement | null>(null)

    const handleScroll = () => {
        const {top} = placeholder.current!.getBoundingClientRect()
        if (top <= 0) {
            // 吸顶
            content.current!.classList.add('fixed')
            placeholder.current!.style.height = `${height}px`
        } else {
            // 取消吸顶
            content.current!.classList.remove('fixed')
            placeholder.current!.style.height = `0px`
        }
    }

    useEffect(() => {
        window.addEventListener('scroll', handleScroll)

        return () => {
            window.removeEventListener('scroll', handleScroll)
        }
    }, [])

    return (
        <>
            <div ref={placeholder}></div>
            <div ref={content}>{children}</div>
        </>
    )
}

export default Sticky
